<template>
  <div>
    <Card>
      <p slot="title"
         style="font-size: 16px;">
        {{this.$route.meta.title}}
      </p>
      <Row :gutter="10">
        <Form :model="formValidate"
              ref="formValidate"
              :label-width="90"
              style="margin-left:20px; width:90%">
          <FormItem label="商品名称"
                    prop="name"
                    class="label_required">
            <Input v-model="formValidate.name"
                   style="width: 500px;"
                   placeholder="请输入商品名称"/>
          </FormItem>
          <FormItem label="商品类别"
                    prop="cate_id"
                    class="label_required">
            <Select v-model="formValidate.cate_id"
                    style="width: 500px;"
                    filterable
                    placeholder="请选择商品类别">
              <Option :value="item.id"
                      v-for="(item, index) in cate_list"
                      :key="index">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="商品图片"
                    prop="img"
                    class="label_required"
                    v-if="formValidate.is_dl!=1">
            <div class="clearfix live_cover">
              <div style="float: left;margin-right: 18px; max-width:350px">
                <template>
                  <draggable v-model="img_arr"
                             @update="datadragEnd"
                             :options="{animation:500}">
                    <transition-group>
                      <div class="demo-upload-list"
                           v-if="img_arr.length"
                           style="margin-right:10px"
                           v-for="(item, index) in img_arr"
                           :key="item">
                        <img :src="item"
                             style='width:100px; height:100px;object-fit: cover;'
                             class="good_img">
                        <div class="demo-upload-list-cover">
                          <Icon type="ios-eye-outline"
                                @click.native="handleView(item)"></Icon>
                          <Icon type="ios-trash-outline"
                                @click.native="handleRemove(index)"></Icon>
                        </div>
                      </div>
                    </transition-group>
                  </draggable>
                  <div v-if="img_arr.length == 0">
                    <div class="no_pic">
                      <img src="../../assets/images/expo/pic2.png"
                           alt=""
                           width="24" />
                    </div>
                  </div>
                </template>
              </div>
              <Upload ref="upload"
                      multiple
                      :show-upload-list="false"
                      action="https://up.qiniup.com"
                      :on-format-error="handleFormatError"
                      :on-progress="handleProgress"
                      :on-success="handleSuccess"
                      :on-error="handleError"
                      :format="['jpg', 'png', 'jpeg']"
                      :data="{token:upload_token}"
                      style="float: left;"
                      v-if="img_arr.length < 15 ">
                <Button style="width:80px;height:30px;background:rgba(248,249,250,1);border:1px solid rgba(232,233,237,1);border-radius:2px;">上传文件</Button>
                <p style="color:#999;margin-top: 8px;">建议尺寸: 800*800px,最多上传15张</p>
              </Upload>
            </div>
          </FormItem>
          <FormItem label="商品价格"
                    prop="price"
                    class="label_required">
            <Input v-model="formValidate.price"
                   style="width: 500px;"
                   placeholder="请输入商品价格" />
          </FormItem>
          <FormItem label="商品库存"
                    prop="store"
                    class="label_required">
            <Input v-model="formValidate.store"
                   style="width: 500px;"
                   placeholder="请输入商品库存" />
          </FormItem>
          <FormItem label="商品销量"
                    prop="sale_count"
                    class="label_required">
            <Input v-model="formValidate.sale_count"
                   style="width: 500px;"
                   placeholder="请输入商品销量" />
          </FormItem>
          <FormItem label="排序"
                    prop="sort"
                    class="label_required">
            <Input v-model="formValidate.sort"
                   style="width: 500px;"
                   placeholder="请输入排序值" />
            <span style="color:#f00; margin-left:10px">数值越大优先显示</span>
          </FormItem>
          <FormItem label="商品简介"
                    prop="desc"
                    class="label_required">
            <Input type="textarea"
                 :rows="8"
                 v-model="formValidate.desc"
                 placeholder="请输入商品简介" style="width:80%"/>
          </FormItem>
          <FormItem label="商品详情"
                    prop="detail_info"
                    class="label_required"
                    v-if='!spinShow' style="width:81%">
            <NEditor :msg="formValidate.detail_info"
                     @changeMsg="changeMsg"></NEditor>
          </FormItem>
          <FormItem>
            <Button :loading="saving"
                    type="primary"
                    @click="handleSubmit"
                    style="width: 90px;height: 35px;border-radius: 0;font-size: 14px; margin-left:150px">提交</Button>
          </FormItem>
        </Form>
        <Spin fix
              v-if="spinShow">
          <Icon type="load-d"
                size=30
                class="demo-spin-icon-load"></Icon>
          <div>数据加载中</div>
        </Spin>
      </Row>
    </Card>
    <Modal title="查看图片"
           v-model="visible">
      <img :src="imgName"
           v-if="visible"
           style="width: 100%">
    </Modal>
  </div>
</template>
<script>

import draggable from 'vuedraggable'
import VueNeditorWrap from 'vue-neditor-wrap'
import { getQiniu, editGood, goodCateForSelect, getGoodDetail} from '@/api/main'
export default {
  data () {
    return {
      spinShow: true,
      cate_list: [],
      isSubmiting: false,
      saving: false,
      upload_token: '',
      qiniu_url: '',
      visible: false,
      imgName: '',
      formValidate: {
        id: 0,
        cate_id: 0,
        name: '',
        img: '',
        imgs: '',
        price: 0,
        store: 0,
        sale_count: 0,
        desc: '',
        detail_info: '',
        sort: 0,
      },
      img_arr: [],
    }
  },
  components: {
    draggable,
    VueNeditorWrap
  },
  methods: {
    changeMsg (msg) {
      this.formValidate.detail_info = msg
    },
    getGoodInfo() {
      let _this = this
      if (parseInt(this.$route.params.id)) {
        let good_obj = {}
        good_obj.id = _this.$route.params.id
        getGoodDetail(good_obj).then(res => {
          this.formValidate = Object.assign({}, res.data)
          this.img_arr = this.formValidate.imgs.split(',')
          this.$route.meta.title = '编辑商品'
          this.edit = true
          setTimeout(() => {
            this.spinShow = false
          }, 1)
        })
      } else {
        _this.spinShow = false
      }
    },
    handleReset (name) {
      this.$refs[name].resetFields()
    },
    handleSubmit () {
      let _this = this
      if (this.formValidate.name == '') {
        this.$Message.error("请输入商品名称"); return;
      }
      if (this.formValidate.cate_id == 0) {
        this.$Message.error("请选择商品类别"); return;
      }
      if (this.img_arr.length == 0) {
        this.$Message.error("请上传商品图片"); return;
      }
      if (!this.formValidate.price) {
        this.$Message.error("请输入商品价格"); return;
      }
      if (!this.formValidate.store) {
        this.$Message.error("请输入商品库存"); return;
      }
      if (this.formValidate.desc == '') {
        this.$Message.error("请输入商品简介"); return;
      }
      if (this.formValidate.detail_info == '') {
        this.$Message.error("请输入商品详情"); return;
      }
      let aEls = document.getElementsByClassName('good_img');
      let img_arr = Array.from(aEls)
      let new_img_arr = []
      img_arr.forEach((item, index) => {
        new_img_arr.push(item.currentSrc)
      })
      this.formValidate.img = new_img_arr[0]
      this.formValidate.imgs = new_img_arr.join(',')
      if (this.isSubmiting) {
        return
      }
      this.isSubmiting = true
      editGood(this.formValidate).then(res => {
        if (res.code === 0) {
          this.$Message.success('操作成功')
        } else {
          this.$Message.error(res.text)
        }
        setTimeout(() => {
          this.isSubmiting = false
        }, 1000);
      })
    },
    handleFormatError (file) {
      this.$Message.error('文件 ' + file.name + ' 格式不正确，请选择图片文件。')
    },
    handleProgress (event, file) { },
    handleSuccess (event, file, fileList) {
      this.img_arr.push(file.response.domain + file.response.key)
    },
    handleError (event, file) { },
    handleView (img_url) {
      this.imgName = img_url
      this.visible = true
    },
    handleRemove (index) {
      this.img_arr.splice(index, 1)
    },
    async init () {
      let qiniu = await getQiniu()
      this.upload_token = qiniu.token
      this.qiniu_url = qiniu.url
    },
    datadragEnd (evt) {
      evt.preventDefault();
    }
  },
  mounted () {
    this.init()
    this.getGoodInfo()
    goodCateForSelect().then(res => {
      if (res.code == 0) {
        this.cate_list = res.data
      }
    })
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    }
  }
}
</script>
<style>
.edui-notadd .edui-dialog {
	z-index: 2005 !important;
}
</style>
<style scoped lang="less">
/deep/ .edui-notadd .edui-dialog {
	z-index: 5000 !important;
}
/deep/ input::-webkit-input-placeholder {
	color: rgba(153, 153, 153, 0.47) !important;
	font-size: 14px !important;
}
/deep/ input::-moz-placeholder {
	color: rgba(153, 153, 153, 0.47) !important;
	font-size: 14px !important;
}
/deep/ input:-moz-placeholder {
	color: rgba(153, 153, 153, 0.47) !important;
	font-size: 14px !important;
}
/deep/ input:-ms-input-placeholder {
	color: rgba(153, 153, 153, 0.47) !important;
	font-size: 14px !important;
}
</style>
